<?php
/**
 * Created by PhpStorm.
 * User: liyan
 * Date: 2019/3/15
 * Time: 14:17
 */

namespace app\m\controller;

use think\Db;

class Assess
{
    //学校类型对应年级
    private $class_type = [
        2 => [
            ['id' => 1, 'name' => '一年级'],
            ['id' => 2, 'name' => '二年级'],
            ['id' => 3, 'name' => '三年级'],
            ['id' => 4, 'name' => '四年级'],
            ['id' => 5, 'name' => '五年级'],
            ['id' => 6, 'name' => '六年级']],
        3 => [
            ['id' => 1, 'name' => '一年级'],
            ['id' => 2, 'name' => '二年级'],
            ['id' => 3, 'name' => '三年级'],
            ['id' => 4, 'name' => '四年级'],
            ['id' => 5, 'name' => '五年级'],
            ['id' => 6, 'name' => '六年级'],
            ['id' => 7, 'name' => '七年级'],
            ['id' => 8, 'name' => '八年级'],
            ['id' => 9, 'name' => '九年级']],
        4 => [
            ['id' => 7, 'name' => '七年级'],
            ['id' => 8, 'name' => '八年级'],
            ['id' => 9, 'name' => '九年级']],
        5 => [
            ['id' => 7, 'name' => '七年级'],
            ['id' => 8, 'name' => '八年级'],
            ['id' => 9, 'name' => '九年级'],
            ['id' => 10, 'name' => '高一'],
            ['id' => 11, 'name' => '高二'],
            ['id' => 12, 'name' => '高三']],
        6 => [
            ['id' => 10, 'name' => '高一'],
            ['id' => 11, 'name' => '高二'],
            ['id' => 12, 'name' => '高三']]
    ];
    private $ask_minute = [
        10 => 2,      //足球课
        11 => 3,      //大课间
        14 => 1,      //班级联赛
        16 => 2       //文化节
    ];
    private $refuse_text = ['文件/图片格式不正确', '上传内容不完整', '图片太过模糊', '内容和要求不符'];


    public function auth()
    {
        session('ses', ['oid' => 2, 'uid' => 2]);
    }

    //学校考核内容查询
    public function school_assess()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $sid = isset($_GET['sid']) ? intval($_GET['sid']) : 0;


        $now = $_SERVER['REQUEST_TIME'];

        $qs = Db::query('select id,pid,grade,title,intro,example,time from x1_assess');
        $assess = [];

        foreach ($qs as $v) {
            $v['example'] = $v['example'] ? json_decode($v['example'], true) : [];
            $assess[$v['id']] = $v;
        }

        //获取学校信息
        if (!$sid) {
            $qs = Db::query('select id from x1_user_role where uid=? and state=1', [$uid]);
            if (!$qs) {
                echo '{"err":3,"msg":"没有绑定任何角色"}';
                return;
            }
            $qs = Db::query('select s.id,s.name,s.type from x1_user_role r left join x1_school s on r.pid=s.id where r.uid=? and r.state=1 and r.type in (2,3)', [$uid]);
            if (!$qs) {
                echo json_encode(['err' => 4, 'msg' => '您没有认证校园用户']);
                return;
            }
            $role = $qs[0];
            $sid = $role['id'];
            $school = $role;
            $roles = $qs;
            $school['class_group'] = $this->class_type[$school['type']];
        } else {
            $qs = Db::query('select s.id,s.name,s.type from x1_user_role r left join x1_school s on r.pid=s.id where s.id=? and r.state=1 and r.type in (2,3)', [$sid]);
            if (!$qs) {
                echo '{"err":1001,"msg":"学校信息不存在"}';
                return;
            }
            $sid = $qs[0]['id'];
            $school = $qs[0];
            $roles = $qs;
            $school['class_group'] = $this->class_type[$school['type']];
        }
        //获取学校考核信息
        $year = date('Y', $now);
        $qs = Db::query('select id,grade,grade_detail from x1_school_assess  where sid=? and `year`=?', [$sid, $year]);
        if (!$qs) {
            $data = ['sid' => $sid, 'year' => $year, 'grade' => 0, 'grade_detail' => '', 'is_achieve' => 0, 'time' => $now];
            $id = Db::table('x1_school_assess')->insertGetId($data);
            $data['id'] = $id;
            $school = array_merge($school, $data);
        } else {
            $data = $qs[0];
            $school = array_merge($school, $data);
        }
        //获取上传文件信息
        $school['title'] = $school['name'] . $year . '年度考核表';
        //学校组织
        $qs = Db::query('select id,name,file,thumb,type,msg,result,uid,aid from x1_assess_lead where pid=? and result!=6 order by id', [$school['id']]);
        $a1 = $qs;
        //体育课
        $qs = Db::query('select id,name,file,thumb,type,result,msg,class_type,aid from x1_assess_gym where pid=? and result!=6', [$school['id']]);
        $a2 = $qs;
        //大课间
        $qs = Db::query('select id,name,file,thumb,type,result,msg,term,aid from x1_assess_time where pid=? and result!=6', [$school['id']]);
        $a3 = $qs;
        //班级联赛
        $qs = Db::query('select id,name,file,thumb,type,aid,result,msg from x1_assess_league where pid=? and result!=6', [$school['id']]);
        $a4 = $qs;
        //足球文化节
        $qs = Db::query('select id,name,file,thumb,type,aid,result,msg from x1_assess_culture where pid=? and result!=6', [$school['id']]);
        $a5 = $qs;

        if (!$school['grade_detail']) {
            $grade_detail = [0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0];

        } else {
            $grade_detail = json_decode($school['grade_detail'], true);
        }
        $lead = [6 => [], 7 => [], 8 => []];
        foreach ($a1 as $v) {
            if (!$school['grade_detail']) {
                if ($v['aid'] == 6 && $v['result'] == 2) {
                    $grade_detail[6] = 2;
                }
                if ($v['aid'] == 7 && $v['result'] == 2) {
                    $grade_detail[7] = 4;
                }
                if ($v['aid'] == 8 && $v['result'] == 2) {
                    $grade_detail[8] = 4;
                }
            }
            $lead[$v['aid']][] = $v;
        }
        $grade_detail[1] = $grade_detail[6] + $grade_detail[7] + $grade_detail[8];

        $gym = [9 => [], 10 => []];
        foreach ($a2 as $v) {
            if (!$school['grade_detail']) {
                if ($v['aid'] == 9 && $v['result'] == 2) {
                    $grade_detail[9] = 2;
                }
                if ($v['aid'] == 10 && $v['result'] == 2) {
                    $grade_detail[10] = 4;
                }
            }
            $gym[$v['aid']][] = $v;
        }
        $grade_detail[2] = $grade_detail[9] + $grade_detail[10];

        $playtime = [11 => []];
        foreach ($a3 as $v) {
            if (!$school['grade_detail']) {
                if ($v['aid'] == 11 && $v['result'] == 2 && $v['term'] == 1 && $v['type'] == 2) {
                    $grade_detail[11] += 10;
                }
                if ($v['aid'] == 11 && $v['result'] == 2 && $v['term'] == 2 && $v['type'] == 2) {
                    $grade_detail[11] += 10;
                }
            }
            $playtime[$v['aid']][] = $v;
        }
        $grade_detail[3] = $grade_detail[11];

        $league = [12 => [], 13 => [], 14 => []];
        foreach ($a4 as $v) {
            if (!$school['grade_detail']) {
                if ($v['aid'] == 12 && $v['result'] == 2) {
                    $grade_detail[12] = 4;
                }
                if ($v['aid'] == 13 && $v['result'] == 2) {
                    $grade_detail[13] = 4;
                }
                if ($v['aid'] == 14 && $v['result'] == 2) {
                    $grade_detail[14] = 12;
                }
            }
            $league[$v['aid']][] = $v;
        }
        $grade_detail[4] = $grade_detail[12] + $grade_detail[13] + $grade_detail[14];

        $culture = [15 => [], 16 => [], 17 => []];
        foreach ($a5 as $v) {
            if (!$school['grade_detail']) {
                if ($v['aid'] == 15 && $v['result'] == 2) {
                    $grade_detail[15] = 5;
                }
                if ($v['aid'] == 16 && $v['result'] == 2) {
                    $grade_detail[16] = 10;
                }
                if ($v['aid'] == 17 && $v['result'] == 2) {
                    $grade_detail[17] = 5;
                }
            }
            $culture[$v['aid']][] = $v;
        }
        $grade_detail[5] = $grade_detail[15] + $grade_detail[16] + $grade_detail[17];

        $grade_detail[0] = $grade_detail[1] + $grade_detail[2] + $grade_detail[3] + $grade_detail[4] + $grade_detail[5];

        if (!$school['grade_detail']) {
            Db::execute('update x1_school_assess set grade=?,grade_detail=? where id=?', [$grade_detail[0], json_encode($grade_detail), $data['id']]);
        }


        $rules = "1. 本次考核共100分，分为五大项，12小项。<br/>2. 考核内容的上传/修改时间一般为本年,点击每一项的‘添加图片’区域查看每项的上传要求。<br/>3. 除特殊要求，各项均可上传文件/图片，且至少上传一个。文件可以上传word,excel,pdf格式。<br/>4. 已上传的文件/图片都可以点击图标预览，长按图标删除，审核失败的文件可以通过点击图标查看失败原因。<br/>5. 同一所学校的校长和教师都可以编辑此考核。<br/>6. 文件/图片提交后，会由上级人员核验，结果会通过系统通知发送给此文件的上传者，并且所有此学校成员会在考核页面查看审核结果。<br/>7. 第二大项'体育课'与其他部分不同，即有一个年级的所有文件/图片不通过或者未上传则扣三分，扣完此小项分数为止。<br/>8. 第三项'大课间'的图片上传可选，此项的图片只是参考，不影响分数。<br/>";
        echo json_encode(['err' => 0, 'msg' => '获取考核信息成功', 'school' => $school, 'assess' => $assess, 'grade_detail' => $grade_detail, 'lead' => $lead, 'gym' => $gym, 'culture' => $culture, 'league' => $league, 'playtime' => $playtime, 'rules' => $rules, 'roles' => $roles]);


//        return view('upload',['school'=>$school,'assess'=>$assess,'grade_detail'=>$grade_detail,'lead'=>$lead,'gym'=>$gym,'culture'=>$culture,'league'=>$league,'playtime'=>$playtime,'rules'=>$rules,'roles'=>$roles]);
    }

    //考核标准
    public function assess_rules()
    {
        $rules = '';
        echo json_encode(['err' => 0, 'msg' => '获取规则成功', 'rules' => $rules]);
    }

    public function assess_ask()
    {
        $code = isset($_GET['code']) ? trim($_GET['code']) : '';
        if ($code) {
            $user = json_decode($this->unescape($code), true);
            session('ses', ['uid' => $user['uid'], 'oid' => $user['id']]);

        }
        $ses = session('ses');
        $assess = $_GET['assess'] ? $_GET['assess'] : 'lead';
        $aid = $_GET['aid'];
        $pid = $_GET['pid'];
        $title = $_GET['title'];
        $class_type = $_GET['class_type'];
        $term = $_GET['term'];


        $qs = Db::query('select intro from x1_assess where id=?', [$aid]);
        $ask = $qs ? $qs[0]['intro'] : '';

        return view('upload', ['assess' => $assess, 'aid' => $aid, 'title' => $title, 'class_type' => $class_type, 'term' => $term, 'ask' => $ask, 'pid' => $pid]);

    }


    //文件上传,word,png.excel,mp4
    public function file_upload()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];

        $type = isset($_POST['type']) ? intval($_POST['type']) : 0;
        $assess = isset($_POST['assess']) ? addslashes($_POST['assess']) : 'lead';
        $pid = isset($_POST['pid']) ? intval($_POST['pid']) : 0;
        $term = isset($_POST['term']) ? intval($_POST['term']) : 1;
        $class_type = isset($_POST['class_type']) ? intval($_POST['class_type']) : 1;
        $filetype = 1;
        $now = $_SERVER['REQUEST_TIME'];
        if (!$_FILES) {
            echo '{"err":1003,"msg":"文件大小不符合规范"}';
            return;
        }
        $err = $_FILES['file']['error'];

        $file = request()->file('file');

        if ($err) {
            echo '{"err":2,"msg":"上传失败"}';
            $ip = $_SERVER['REMOTE_ADDR'];
            $json = ['err' => 2, 'msg' => '上传失败', 'time' => date('Y-m-d H:i:s', $now), 'file' => $_FILES];
            loger('vod    ' . $ip, 'xzb');
            return;
        }
        //$vodpath = ROOT_PATH.'app'.DS.'xzb'.DS.'vod';
        $picpath = ROOT_PATH . 'm' . DS . 'xzb' . DS . 'uploads' . DS . 'assess';
        $path = 'https://x.g56.cn/xzb/uploads/assess';
        $info = $file->move($picpath);
        $filename = $info->getInfo('name');


        if ($info) {
            $saveName = $info->getSaveName();
            if (strpos($saveName, '\\') > -1) {
                $saveName = str_replace('\\', '/', $saveName);
            }
            $pic_path = $path . DS . $saveName;// 线上环境 图片上传地址
            $p = strrpos($saveName, '.');
            $thumbName = substr($saveName, 0, $p) . '_thumb.png'; // 缩略图
            $thumbPath = $picpath . DS . $thumbName;
            $ext = strtolower(pathinfo($pic_path, PATHINFO_EXTENSION));
            //生成缩略图
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pic'])) {
                //图片
                list($width, $height, $picType, $attr) = getimagesize($picpath . DS . $saveName);
                $im = img_create($picpath . DS . $saveName, $picType);
                $images = imagecreatetruecolor(200, 200);
                imagecopyresampled($images, $im, 0, 0, 0, 0, 200, 200, $width, $height);
                imagepng($images, $thumbPath);
                imagedestroy($images);
                $thumb_path = $path . DS . $thumbName;
            } elseif (in_array($ext, ['mp4', 'rm', 'avi', 'mov', 'asf'])) {
                //视频
                $filetype = 2;
                $thumb_path = 'https://x.g56.cn/xzb/images/video.png';
            } elseif (in_array($ext, ['doc', 'docx'])) {
                $filetype = 3;
                $thumb_path = 'https://x.g56.cn/xzb/images/doc.png';
            } elseif ($ext == 'pdf') {
                $filetype = 3;
                $thumb_path = 'https://x.g56.cn/xzb/images/pdf.png';
            } elseif (in_array($ext, ['xls', 'xlsx'])) {
                $filetype = 3;
                $thumb_path = 'https://x.g56.cn/xzb/images/xls.png';
            } else {
                $filetype = 3;
                $thumb_path = 'https://x.g56.cn/xzb/images/txt.png';
            }
        }

        switch ($assess) {
            case 'lead':
                $id = Db::table('x1_assess_lead')->insertGetId(['uid' => $uid, 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'pid' => $pid, 'aid' => $type, 'type' => $filetype, 'time' => $now]);
                break;
            case 'gym':
                $id = Db::table('x1_assess_gym')->insertGetId(['uid' => $uid, 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'pid' => $pid, 'aid' => $type, 'type' => $filetype, 'class_type' => $class_type, 'time' => $now]);
                break;
            case 'playtime':
                $id = Db::table('x1_assess_time')->insertGetId(['uid' => $uid, 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'pid' => $pid, 'aid' => $type, 'type' => $filetype, 'term' => $term, 'time' => $now]);
                break;
            case 'league':
                $id = Db::table('x1_assess_league')->insertGetId(['uid' => $uid, 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'pid' => $pid, 'aid' => $type, 'type' => $filetype, 'time' => $now]);
                break;
            case 'culture':
                $id = Db::table('x1_assess_culture')->insertGetId(['uid' => $uid, 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'pid' => $pid, 'aid' => $type, 'type' => $filetype, 'time' => $now]);
                break;
            default:
                $id = 0;
                break;
        }
        echo json_encode(['err' => 0, 'msg' => '上传成功', 'name' => $filename, 'file' => $pic_path, 'thumb' => $thumb_path, 'id' => $id, 'type' => $filetype, 'pid' => $pid, 'aid' => $type]);
    }
    /*    //某个用户所有学校角色
        public function user_school_list(){
            $ses=session('ses');
            if(!$ses){
                echo '{"err":1,"msg":"param error"}';
                return;
            }
            $uid=$ses['uid'];
            $list=Db::query('select s.id,s.name from x1_user_role r left join x1_school s on r.pid=s.id where r.uid=? and r.state=1 and r.type in (2,3)',[$uid]);
            echo json_encode(['err'=>0,'msg'=>'获取用户所有学校成功','list'=>$list]);
        }*/


    //删除文件
    public function del_file()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $assess = isset($_GET['assess']) ? addslashes($_GET['assess']) : '';

        if (!$id || !$assess) {
            echo '{"err":1001,"msg":"param request"}';
            return;
        }
        $assess = $assess == 'playtime' ? 'time' : $assess;
        $table = 'x1_assess_' . $assess;
        $qs = Db::table($table)->field('uid,id,pid')->where('id', $id)->select();
        if (!$qs) {
            echo '{"err":1002,"msg":"文件信息未找到"}';
            return;
        }
        $file = $qs[0];
        if (!Db::query('select * from x1_user_role r left join x1_school s on r.pid=s.id left join x1_school_assess a on s.id=a.sid where r.type in (2,3) and r.state=1 and a.id=? and r.uid=?', [$file['pid'], $uid])) {
            echo '{"err":1003,"msg":"您没有权限删除此文件"}';
            return;
        }
        Db::execute('update ' . $table . ' set result=6 where id=?', [$id]);

        echo '{"err":0,"msg":"删除成功"}';
    }

    //获取当前用户的学校考核列表
    public function school_list()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $m = isset($_GET['m']) ? intval($_GET['m']) : 0;
        $now = $_SERVER['REQUEST_TIME'];
        $year = date('Y', $now);
        $list = Db::query('select s.name,s.id,a.grade,a.year from x1_user_role r left join x1_school s on r.pid=s.id left join x1_school_assess a on s.id=a.sid  where r.uid=? and r.type in (2,3) and r.state=1 ', [$uid]);

        $list = array_unique($list, SORT_REGULAR);
        foreach ($list as $k => $v) {
            if ($v['year'] && $v['year'] != $year) {
                unset($list[$k]);
            }
            $list[$k]['grade'] = $v['grade'] ? $v['grade'] : 0;
        }
        echo json_encode(['err' => 0, 'msg' => '获取成功', 'list' => $list]);
    }

    public function get_reason()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $assess = isset($_GET['assess']) ? addslashes($_GET['assess']) : 'lead';
        $assess = $assess == 'playtime' ? 'x1_assess_time' : 'x1_assess_' . $assess;

        $qs = Db::table($assess . ' l')->field('l.thumb,l.file,l.msg,l.result,l.aid,s.name,sa.year')->join('x1_school_assess sa', 'l.pid=sa.id', 'LEFT')->join('x1_school s', 'sa.sid=s.id', 'LEFT')->where('l.id', $id)->select();

        if (!$qs) {
            echo '{"err":1001,"msg":"没有此文件数据"}';
            return;
        }
        $file = $qs[0];
        $qs = Db::table('x1_assess a')->field('concat_ws(",",s.title,a.title) title')->join('x1_assess s', 'a.pid=s.id', 'LEFT')->where('a.id', $file['aid'])->select();
        $file['title'] = $qs ? $qs[0]['title'] : '';

        echo json_encode(['err' => 0, 'msg' => '获取信息成功', 'file' => $file]);
    }


    //审核
    public function check_assess()
    {

    }

    public function change_school_grade()
    {


    }


    public function unescape($str)
    {
        $str = rawurldecode($str);
        preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U", $str, $r);
        $ar = $r[0];
        foreach ($ar as $k => $v) {
            if (substr($v, 0, 2) == "%u")
                $ar[$k] = iconv("UCS-2", "utf-8", pack("H4", substr($v, -4)));
            elseif (substr($v, 0, 3) == "&#x")
                $ar[$k] = iconv("UCS-2", "utf-8", pack("H4", substr($v, 3, -1)));
            elseif (substr($v, 0, 2) == "&#") {
                $ar[$k] = iconv("UCS-2", "utf-8", pack("n", substr($v, 2, -1)));
            }
        }
        return join("", $ar);
    }


    public function test()
    {
        session('ses', ['oid' => 2, 'uid' => 2]);
    }


}